package com.gao.wechat.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.gao.wechat.util.CheckoutUtil;
import com.gao.wechat.util.WeChatUtil;
import com.gao.wechat.vo.WeChatReply;


@Controller
@RequestMapping("wechat/message")
public class WechantMessageController 
{
	
	private String getPreTaskTip(String token) 
	{
        return "<a href=\"" + "http://gaoyijing.iok.la/wechat/login" + "\">点我领红包，最高99元 " + "</a>";
    }
	
	/**
	 * 校验
	 * @param appid
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/wechat/{appid}", method = RequestMethod.GET)
	public void doGet(@PathVariable("appid") String appid,HttpServletRequest request, HttpServletResponse response)
	{
		System.out.println(System.currentTimeMillis());
		boolean isGet = request.getMethod().toLowerCase().equals("get");
        PrintWriter print;
        if (isGet) {
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 随机字符串
            String echostr = request.getParameter("echostr");
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (signature != null && CheckoutUtil.checkSignature(signature, timestamp, nonce)) {
                try {
                    print = response.getWriter();
                    print.write(echostr);
                    print.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
	}
	
	/**
	 * 
	 * @param appid
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/wechat/{appid}", method = RequestMethod.POST)
	public void doPost(@PathVariable("appid") String appid,HttpServletRequest request, HttpServletResponse response)
	{
		String openid = request.getParameter("openid");
		try
		{
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=UTF-8");
			InputStream inputStream = request.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			String buffer;
			StringBuffer sb = new StringBuffer();
			while ((buffer = br.readLine()) != null)
			{
				sb.append(buffer);
			}
			br.close();
			inputStream.close();
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	        DocumentBuilder builder = factory.newDocumentBuilder();
			StringReader sr = new StringReader(sb.toString());
            InputSource is = new InputSource(sr);
            Document document = builder.parse(is);
            Element xmlElement = (Element) document.getElementsByTagName("xml").item(0);
            NodeList nodeList = xmlElement.getChildNodes();
            Map<String, String> dataMap = new HashMap<>();
            for (int i = 0; i < nodeList.getLength(); i++) 
            {
                Node node = nodeList.item(i);
                int nodeType = node.getNodeType();
                if (nodeType == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    String nodeName = element.getNodeName();
                    String value = element.getTextContent();
                    dataMap.put(nodeName, value);
                }
            }
			String msgType = dataMap.get("MsgType");  //消息类型
			if("event".equals(msgType)) 
			{
				String eventType = dataMap.get("Event");
				System.out.println("事件："+eventType);
				if("subscribe".equals(eventType)) 
				{
					//关注
					PrintWriter out = response.getWriter();
					WeChatReply reply = new WeChatReply();
					reply.setToUserName(openid);
					reply.setFromUserName(appid);
					reply.setCreateTime();
					reply.setMsgType("text");
					reply.setContent("欢迎关注!回复666有红包领哦.");
					out.println(WeChatUtil.toXml(reply));// 回复
				}
			}else if("text".equals(msgType))
			{
				String content = dataMap.get("Content");
				if("666".equals(content)) 
				{
					PrintWriter out = response.getWriter();
					WeChatReply reply = new WeChatReply();
					reply.setToUserName(openid);
					reply.setFromUserName(appid);
					reply.setCreateTime();
					reply.setMsgType("text");
					reply.setContent(getPreTaskTip(null));
					out.println(WeChatUtil.toXml(reply));// 回复
				}
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
}
